<template>
  <div>
    <el-form :model="cmsArticle" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="标题" prop="title">
        <el-input v-model="cmsArticle.title" maxlength="100" show-word-limit />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="cmsArticle.sort" :min="1" :max="1000" />
      </el-form-item>
      <el-form-item label="主图" prop="image">
        <MultiImageUpload v-model="cmsArticle.image" limit="1" :showTip="true" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId" v-if="hasCategory">
        <SelectCategory
          @update:modelValue="handleCategoryId"
          v-model:modelValue="cmsArticle.categoryId"
        />
      </el-form-item>
      <slot></slot>
      <el-form-item label="内容" prop="text">
        <div style="height: calc(100vh - 500px); overflow: scroll" class="editor-box">
          <WangEditor v-model="cmsArticle.text" />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, defineEmits } from "vue";
const { proxy } = getCurrentInstance();
import SelectCategory from "../selectCategory/index.vue";

const props = defineProps({
  defaultData: {
    type: Object,
    default: () => {},
  },
  hasCategory: {
    type: Boolean,
    default: true,
  },
});
const cmsArticle = ref({
  title: "",
  sort: 1,
  categoryId: "",
  image: "",
  text: "",
});

const rules = ref({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择分类", trigger: "change" }],
  image: [{ required: true, message: "请上传主图", trigger: "change" }],
  text: [{ required: true, message: "请输入内容", trigger: "change" }],
});

// 选择分类操作
const handleCategoryId = (categoryId) => {
  cmsArticle.value.categoryId = categoryId;
};
// 提供一个方法让父组件获取 formRef
const getEditorFormRef = () => {
  return proxy.$refs["formRef"];
};
watch(
  () => props.defaultData,
  (newVal) => {
    nextTick(() => {
      cmsArticle.value = newVal;
      cmsArticle.value.image = JSON.parse(newVal.image);
    });
  }
);
// 暴露方法给父组件使用
defineExpose({
  getEditorFormRef,
  cmsArticle,
});
</script>

<style lang="scss" scoped>
/* 自定义代码块样式 */
.editor-box {
  width: 100%;
  :deep(code) {
    white-space: pre-wrap !important; /* 保留换行符和空格，同时允许自动换行 */
    word-wrap: break-word !important; /* 允许在单词内换行 */
    overflow: auto !important; /* 超出部分显示滚动条 */
  }
}
</style>
